package practice;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;

public class Kuohao {
    public static void main(String[] args) {
        StringBuffer s = new StringBuffer("i am a  good boy.");
        System.out.println(replaceSpace(s));
        System.out.println(replceSpace2(s));
    }
    public static boolean check(String s){
        Stack<Character> stack = new Stack<Character>();
        char l;
        for(int i=0;i<s.length();i++){
            if (stack.empty()){
                stack.push(s.charAt(i));
                continue;
            }
            if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
                stack.push(s.charAt(i));
            }
            if(s.charAt(i) == ')' || s.charAt(i) == ']' || s.charAt(i) == '}'){
                l = stack.pop();
                switch (s.charAt(i)){
                    case ')':
                        if(l != '(')
                            return false;
                        break;
                    case ']':
                        if (l != '[')
                            return false;
                        break;
                    case '}':
                        if (l != '{')
                            return false;
                        break;
                }
            }
        }
        if (stack.empty())
            return true;
        return false;
    }
    public static String replceSpace2(StringBuffer str){
        return str.toString().replaceAll(" " , "%20");
    }

    public static String replaceSpace(StringBuffer str) {
        if (str == null) {
            return null;
        }
        int length = str.length();
        int indexOfOriginal = length-1;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ')
                length += 2;
        }
        str.setLength(length);
        int indexOfNew = length-1;
        while (indexOfNew > indexOfOriginal) {
            if (str.charAt(indexOfOriginal) != ' ') {
                str.setCharAt(indexOfNew--, str.charAt(indexOfOriginal));
            } else {
                str.setCharAt(indexOfNew--, '0');
                str.setCharAt(indexOfNew--, '2');
                str.setCharAt(indexOfNew--, '%');
            }
            indexOfOriginal--;
        }
        return str.toString();
    }

    private static final Map<Character,Character> map = new HashMap<Character,Character>(){{
        put('{','}'); put('[',']'); put('(',')'); put('?','?');
    }};
    public boolean isValid(String s) {
        if(s.length() > 0 && !map.containsKey(s.charAt(0))) return false;
        LinkedList<Character> stack = new LinkedList<Character>() {{ add('?'); }};
        for(Character c : s.toCharArray()){
            if(map.containsKey(c)) stack.addLast(c);
            else if(map.get(stack.removeLast()) != c) return false;
        }
        return stack.size() == 1;
    }

}
